package com.david.scan

import android.Manifest
import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.BitmapFactory
import android.os.Build
import android.os.Bundle
import android.os.Environment
import android.provider.MediaStore
import android.view.KeyEvent
import android.view.View
import android.view.View.OnClickListener
import android.view.inputmethod.InputMethodManager
import android.widget.EditText
import android.widget.ImageView
import android.widget.TextView
import android.widget.TextView.OnEditorActionListener
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.david.scan.king.util.CodeUtils
import com.google.zxing.BarcodeFormat
import com.king.camera.scan.util.LogUtils
import com.king.camera.scan.util.PermissionUtils
import java.util.concurrent.Executors


class CreateQrActivity:Activity(), OnClickListener {
    private lateinit var pic: ImageView  //展示二维码
    private lateinit var showText: TextView //显示二维码的内容
    private lateinit var editText: EditText
    private var bitmap: Bitmap? = null //声明一个bitmap对象用于放置图片;

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_qr_create)

        initView()
    }

    private fun initView() {
        pic = findViewById<View>(R.id.pic) as ImageView
        showText = findViewById<View>(R.id.show_txt) as TextView
        editText = findViewById(R.id.edit_qr)
        findViewById<View>(R.id.create_qr_btn).setOnClickListener(this)
        findViewById<View>(R.id.parse_qr_btn).setOnClickListener(this)

        findViewById<View>(R.id.create_bar_btn).setOnClickListener(this)
        findViewById<View>(R.id.parse_bar_btn).setOnClickListener(this)

        editText.setOnEditorActionListener(object :OnEditorActionListener{
            override fun onEditorAction(v: TextView?, actionId: Int, event: KeyEvent?): Boolean {
                if (event?.keyCode == KeyEvent.KEYCODE_ENTER) {
                    createQRCode(v?.text.toString())//默认生成二维码
                    return true
                }
                return false
            }

        })
    }

    override fun onClick(v: View?) {
        when (v!!.id) {
            R.id.create_bar_btn -> {
                createBarCode(editText.text.toString())

                //bitmap = createBarcode(edit_qr.text.toString(), 0,50)
                //pic.setImageBitmap(bitmap)
            }//create_QR_code() //此方法用于创建二维码

            R.id.create_qr_btn -> {
                createQRCode(editText.text.toString())
            }

            R.id.parse_qr_btn, R.id.parse_bar_btn -> {
                pickPhotoClicked()
            }
        }
    }

    private val executor = Executors.newSingleThreadExecutor()

    /**
     * 生成二维码
     * @param content
     */
    private fun createQRCode(content: String) {
        executor.execute {

            //生成二维码相关放在子线程里面
            val logo = BitmapFactory.decodeResource(resources, R.mipmap.ic_launcher)
            val bitmap = CodeUtils.createQRCode(content, 600, logo)
            runOnUiThread {
                this.bitmap = bitmap
                //显示二维码
                pic.setImageBitmap(bitmap)
            }
        }
        hideSoftKeyBoard()
    }

    /**
     * 生成条形码
     * @param content
     */
    private fun createBarCode(content: String) {
        executor.execute {

            //生成条形码相关放在子线程里面
            val bitmap = CodeUtils.createBarCode(content, BarcodeFormat.CODE_128, 800, 200, null, true)
            runOnUiThread {
                this.bitmap = bitmap

                //显示条形码
                pic.setImageBitmap(bitmap)
            }
        }

        hideSoftKeyBoard()
    }


    /**
     * 点击选择图片识别 - 进行动态权限校验
     */
    private fun pickPhotoClicked() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
                startPickPhoto()
            }
        } else {
            if (PermissionUtils.checkPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE)) {
                startPickPhoto()
            } else {
                PermissionUtils.requestPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE, 99)
            }
        }
    }

    private val REQUEST_CODE_PHOTO = 0x02


    /**
     * 开始选择图片
     */
    private fun startPickPhoto() {
        val pickIntent = Intent(Intent.ACTION_PICK,
            MediaStore.Images.Media.EXTERNAL_CONTENT_URI)
        pickIntent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*")
        startActivityForResult(pickIntent, REQUEST_CODE_PHOTO)
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (resultCode == AppCompatActivity.RESULT_OK && data != null) {
            if (requestCode == REQUEST_CODE_PHOTO) {
                parsePhoto(data)
            }
        }
    }

    private fun parsePhoto(data: Intent) {
        try {
            val bitmap = MediaStore.Images.Media.getBitmap(contentResolver, data.data)
            //异步解析
            asyncThread {
                val result = CodeUtils.parseCode(bitmap)
                runOnUiThread {
                    LogUtils.d("result:$result")
                    showToast(result)
                }
            }
        } catch (e: java.lang.Exception) {
            e.printStackTrace()
        }
    }

    private fun asyncThread(runnable: Runnable) {
        executor.execute(runnable)
    }

    private var toast: Toast? = null
    private fun showToast(text: String?) {
        showText.text = "parse result is: $text"
        if (toast != null) {
            toast?.cancel()
        }
        toast = Toast.makeText(this, text, Toast.LENGTH_SHORT)
        toast?.show()
    }

    private fun hideSoftKeyBoard() {
        val inputMethodManager = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        inputMethodManager.hideSoftInputFromWindow(currentFocus!!.windowToken, 0)

    }
}